from . import app_rendering
from flask import render_template, request, redirect
from token_mmwl import Token
from conn_mysql import ConnectMysql
from particular_authority.consumption_notify import ConsumptionNotify


@app_rendering.route('/personal')
def personal():

    get_data = request.args
    token = get_data.get("token")

    if not token: return redirect('/login?msg=请登录')#没有token值重新登录

    token_status = Token().token_status(token)#检测token值合法性

    if token_status['status'] == 1:

        with ConnectMysql() as CM:
            #获取关注的对像，consumption表
            sql = "SELECT * FROM consumption WHERE company_id=%s"
            info = CM.select_all(sql, (token_status["resultBody"]["token_info"]["company_id"],))

            sql_company = "SELECT * FROM company WHERE id=%s"
            consumption_surplus = CM.select_one(sql_company, (token_status["resultBody"]["token_info"]["company_id"],))['consumption_surplus']

            follow_id = [i["consumption_id"] for i in info]#关注的对象的ID
            if follow_id:
                if len(follow_id) == 1:

                    follow_sql = f"SELECT * FROM company WHERE id={follow_id[0]}"
                else:
                    follow_sql = f"SELECT * FROM company WHERE id in {tuple(follow_id)}"
                follow_info = CM.select_all(follow_sql)#取出所有关注对象的company信息

            else:
                float_info = {}
            return render_template("personal.html", 
                                    follow_info = follow_info,
                                    token=token, consumption_surplus = consumption_surplus)

            
    else:

        return redirect(f'/login?msg={token_status["errorMsg"]}')


@app_rendering.route('/follow_detail/<int:ID>')

def follow_detail(ID):

    get_data = request.args

    token = get_data.get("token")

    if not token: return redirect('/login?msg=请登录')#没有token值重新登录

    token_status = Token().token_status(token)#检测token值合法性

    if token_status['status'] == 1:

        with ConnectMysql() as CM:

            sql = "SELECT * FROM consumption WHERE company_id=%s and consumption_id=%s"
            info = CM.select_one(sql, (token_status["resultBody"]["token_info"]["company_id"],ID))

            sql = "SELECT * FROM company WHERE id=%s"
            result_info = CM.select_one(sql, (ID,))

            return render_template("follow_detail.html", token =token,
                                    result_info = result_info)


    else:
    
        return redirect(f'/login?msg={token_status["errorMsg"]}')



